package com.bookbuf.weibo;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.bookbuf.social.PlatformEnum;
import com.bookbuf.social.handlers.ISSOHandler;
import com.bookbuf.social.handlers.SSOHandler;
import com.bookbuf.social.platforms.WeiBoPlatform;
import com.bookbuf.social.share.content.ShareContent;
import com.bookbuf.social.share.content.location.Location;
import com.bookbuf.social.share.content.media.image.ImageMedia;
import com.bookbuf.social.util.QueuedWork;
import com.bookbuf.weibo.content.WeiboShareContent;
import com.bookbuf.weibo.localize.SinaPreferences;
import com.sina.sso.RemoteSSO;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.AsyncWeiboRunner;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.sina.weibo.sdk.utils.LogUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * author: robert.
 * date :  16/8/9.
 */
public class SinaSsoHandler extends SSOHandler<WeiBoPlatform> {

	private static final String TAG = SinaSsoHandler.class.getSimpleName ();
	private static final int REQUEST_CODE = 5659;
	private WeiBoPlatform platform = null;
	private SinaPreferences sinaPreferences;
	private ShareListener shareListener;
	private SinaSsoHandler.AuthListener mAuthListener;
	private Context mContext;
	private SsoHandler mSsoHandler;
	private AuthInfo mAuthInfo;
	public static final String SCOPE = "email,direct_messages_read,direct_messages_write,friendships_groups_read,friendships_groups_write,statuses_to_me_read,follow_app_official_microblog,invitation_write";
	private IWeiboShareAPI mWeiboShareAPI;
	public static String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";

	public SinaSsoHandler () {
	}

	@Override
	public void onCreate (Context context, WeiBoPlatform platform) {
		super.onCreate (context, platform);
		boolean needCreateNewSsoHandler = platform != this.platform && platform != null;
		Log.i (TAG, "onCreate: needCreateNewSsoHandler = " + needCreateNewSsoHandler);
		this.mContext = context;
		this.platform = platform;
		this.sinaPreferences = new SinaPreferences (this.mContext, "sina");
		this.mAuthInfo = new AuthInfo (this.mContext, this.platform.appId, REDIRECT_URL, SCOPE);
		if (this.mContext instanceof Activity && (needCreateNewSsoHandler || this.mSsoHandler == null)) {
			this.mSsoHandler = new SsoHandler ((Activity) context, this.mAuthInfo);
			this.mWeiboShareAPI = WeiboShareSDK.createWeiboAPI (context, this.platform.appId);
			this.mWeiboShareAPI.registerApp ();
		}
	}

	public IWeiboShareAPI getmWeiboShareAPI () {
		return this.mWeiboShareAPI;
	}

	@Override
	public boolean isSupportAuthorize () {
		return true;
	}

	public boolean isAuthorized () {
		return this.sinaPreferences.isAuthorized ();
	}

	public boolean isInstall (Context mContext) {
		return this.isClientInstalled ();
	}

	public boolean isAuthorize (Context mContext) {
		return this.isAuthorized ();
	}

	@Override
	public WeiBoPlatform getPlatform () {
		return this.platform;
	}

	public String getUID () {
		return this.sinaPreferences.getUID ();
	}

	public boolean isClientInstalled () {
		return this.mWeiboShareAPI.isWeiboAppInstalled ();
	}

	@Override
	public void applyAuthorize (Activity act, ISSOHandler.AuthListener listener) {
		this.mAuthListener = new SinaSsoHandler.AuthListener (listener);
		this.mSsoHandler.authorize (this.mAuthListener);
	}

	private void printSsoHandler (SsoHandler handler, String property) {
		Log.i (TAG, "printSsoHandler: +");
		Field fields[] = handler.getClass ().getDeclaredFields ();
		String[] name = new String[fields.length];
		Object[] value = new Object[fields.length];

		try {
			Field.setAccessible (fields, true);
			for (int i = 0; i < name.length; i++) {

				name[i] = fields[i].getName ();
				value[i] = fields[i].get (handler);
				if (name[i].equals (property)) {
					Log.w (TAG, " [" + name[i] + " = " + value[i] + "]");
				}
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
		Log.i (TAG, "printSsoHandler: -");
	}

	protected void requestAsync (String url, WeiboParameters params, String httpMethod, RequestListener listener, String mAccessToken) {
		if (null != mAccessToken && !TextUtils.isEmpty (url) && null != params && !TextUtils.isEmpty (httpMethod) && null != listener) {
			params.put ("access_token", mAccessToken);
			(new AsyncWeiboRunner (this.mContext)).requestAsync (url, params, httpMethod, listener);
		} else {
			LogUtil.e ("SinaSsoHandler", "Argument error!");
		}
	}

	private void getPlatformInfo (final Activity act, final ISSOHandler.AuthListener listener) {
		if (this.sinaPreferences.getUID () != null) {
			WeiboParameters params = new WeiboParameters (this.platform.appId);
			params.put ("uid", this.sinaPreferences.getUID ());
			this.requestAsync ("https://api.weibo.com/2/users/show.json", params, "GET", new RequestListener () {
				public void onComplete (String s) {
					HashMap map = new HashMap ();
					map.put ("result", s);
					listener.onComplete (PlatformEnum.SINA_WEIBO, 2, map);
				}

				public void onWeiboException (WeiboException e) {
					listener.onError (PlatformEnum.SINA_WEIBO, 2, new Throwable (e));
				}
			}, this.sinaPreferences.getmAccessToken ());
		} else {
			this.applyAuthorize (act, new ISSOHandler.AuthListener () {
				public void onComplete (PlatformEnum platform, int action, Map<String, String> data) {
					QueuedWork.runInBack (new Runnable () {
						public void run () {
							SinaSsoHandler.this.getPlatformInfo (act, listener);
						}
					});
				}

				public void onError (PlatformEnum platform, int action, Throwable t) {
					Log.e (TAG, "xxxx 授权失败");
				}

				public void onCancel (PlatformEnum platform, int action) {
					Log.e (TAG, "xxxx 授权取消");
				}
			});
		}
	}

	public void deleteAuth (Context context, ISSOHandler.AuthListener authListener) {
		this.sinaPreferences.delete ();
		authListener.onComplete (PlatformEnum.SINA_WEIBO, 1, null);
	}

	@Override
	public void callApiProfile (Activity activity, ISSOHandler.AuthListener listener) {
		getPlatformInfo (activity, listener);
	}

	@Override
	public void callApiCheckAccessTokenValid (Activity activity, ISSOHandler.AuthListener listener) {
		applyAuthorize (activity, listener);
	}

	@Override
	public boolean share (Activity activity, ShareContent shareContent, final ShareListener listener) {
		if (activity == null) {
			return false;
		} else {

			Log.i (TAG, "share: +" + hashCode ());
			WeiboShareContent content = new WeiboShareContent.WXShareContentWrapper (shareContent).build ();
			content.setContext (activity);

			SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest ();
			request.transaction = String.valueOf (System.currentTimeMillis ());
			request.multiMessage = content.build ();

			AuthInfo authInfo = new AuthInfo (activity, this.platform.appId, REDIRECT_URL, SCOPE);

			String token = "";
			if (this.sinaPreferences != null) {
				token = this.sinaPreferences.getmAccessToken ();
				Log.i (TAG, "share: read token from preference");
			} else {
				Log.i (TAG, "share: preference is empty!!!");
			}

			Log.i (TAG, "share: token = " + token);
			Log.i (TAG, "share: appKey = " + authInfo.getAppKey ());
			Log.i (TAG, "share: REDIRECT_URL = " + REDIRECT_URL);
			Log.i (TAG, "share: SCOPE = " + SCOPE);


			this.shareListener = listener;
			Log.i (TAG, "share: " + hashCode ());
			Log.i (TAG, "share: shareListener = " + shareListener);
			this.mWeiboShareAPI.sendRequest (activity, request, authInfo, token, new WeiboAuthListener () {
				public void onWeiboException (WeiboException arg0) {
					if (shareListener != null) {
						shareListener.onError (PlatformEnum.SINA_WEIBO, new Throwable (arg0));
					}

				}

				public void onComplete (Bundle bundle) {
					if (shareListener != null) {
						shareListener.onResult (PlatformEnum.SINA_WEIBO);
					}

					SinaSsoHandler.this.sinaPreferences.setAuthData (bundle).commit ();
				}

				public void onCancel () {
					if (shareListener != null) {
						shareListener.onCancel (PlatformEnum.SINA_WEIBO);
					}

				}
			});
			Log.i (TAG, "share: -" + hashCode ());
			return true;
		}
	}

	@Override
	public void onActivityResult (int requestCode, int resultCode, Intent intent) {
		super.onActivityResult (requestCode, resultCode, intent);

		Log.i (TAG, "onActivityResult: requestCode = " + requestCode);
		Log.i (TAG, "onActivityResult: resultCode = " + resultCode);
		Log.i (TAG, "onActivityResult: intent = " + intent);
		printSsoHandler (this.mSsoHandler, "mSSOAuthRequestCode");
		if (this.mSsoHandler != null) {
			this.mSsoHandler.authorizeCallBack (requestCode, resultCode, intent);
		}
		this.mSsoHandler = null;
	}

	public boolean isSupportAuth () {
		return true;
	}

	public int getRequestCode () {
		return REQUEST_CODE;
	}

	public void setScope (String[] permissions) {
	}

	private boolean bindRemoteSSOService (Activity activity, String appkey) {
		Log.i (TAG, "bindRemoteSSOService: appKey = " + appkey);
		SinaSsoHandler.SinaConnection serviceConnection = new SinaSsoHandler.SinaConnection (activity, appkey);
		Context ctx = activity.getApplicationContext ();
		Intent intent = new Intent ("com.sina.weibo.remotessoservice");
		List infos = activity.getPackageManager ().queryIntentServices (intent, 0);
		ComponentName componentName = null;
		if (infos != null && infos.size () > 0) {
			ResolveInfo info = (ResolveInfo) infos.get (0);
			componentName = new ComponentName (info.serviceInfo.packageName, info.serviceInfo.name);
		}

		intent.setComponent (componentName);
		return ctx.bindService (intent, serviceConnection, Context.BIND_AUTO_CREATE);
	}

	public Bundle getEditable (ShareContent shareContent) {
		Bundle bundle = new Bundle ();
		bundle.putString ("media", PlatformEnum.SINA_WEIBO.toString ());
		bundle.putString ("title", "分享到新浪微博");
		bundle.putString ("txt", shareContent.mText);
		if (shareContent.mMedia != null && shareContent.mMedia instanceof ImageMedia) {
			File file = ((ImageMedia) shareContent.mMedia).asFileImage ();
			if (file != null) {
				bundle.putString ("pic", file.getAbsolutePath ());
			}
		}

		bundle.putBoolean ("at", true);
		bundle.putBoolean ("location", true);
		bundle.putBoolean ("follow_", false);
		return bundle;
	}

	public ShareContent getResult (ShareContent shareContent, Bundle bundle) {
		shareContent.mText = bundle.getString ("txt");
		if (!bundle.getBoolean ("follow_")) {
			shareContent.mFollow = null;
		}

		if (bundle.getString ("pic") == null && shareContent.mMedia instanceof ImageMedia) {
			shareContent.mMedia = null;
		}

		if (bundle.getSerializable ("location") != null) {
			shareContent.mLocation = (Location) bundle.getSerializable ("location");
		}

		return shareContent;
	}

	public void onResponse (BaseResponse baseResponse) {
		Log.i (TAG, "onResponse: " + hashCode ());
		Log.i (TAG, "onResponse: shareListener = " + shareListener);
		Log.i (TAG, "onResponse: errCode = " + baseResponse.errCode + ":" + baseResponse.errMsg);
		switch (baseResponse.errCode) {
			case 0:
				Log.e (TAG, "weibo share ok");
				if (this.isClientInstalled ()) {
					this.shareListener.onResult (PlatformEnum.SINA_WEIBO);
				}
				break;
			case 1:
				Log.e (TAG, "weibo share cancel");
				this.shareListener.onCancel (PlatformEnum.SINA_WEIBO);
				break;
			case 2:
				Log.e (TAG, "weibo share fail");
				this.shareListener.onError (PlatformEnum.SINA_WEIBO, new Throwable (baseResponse.errMsg));

		}

	}

	private Map<String, String> bundleTomap (Bundle bundle) {
		if (bundle != null && !bundle.isEmpty ()) {
			Set keys = bundle.keySet ();
			HashMap map = new HashMap ();
			Iterator var4 = keys.iterator ();

			while (var4.hasNext ()) {
				String key = (String) var4.next ();
				map.put (key, bundle.getString (key));
			}

			return map;
		} else {
			return null;
		}
	}

	static class SinaConnection implements ServiceConnection {
		private static final String AUTH_SERVICE_NAME = "com.sina.weibo.business.RemoteSSOService";
		private static final String REDIRECT_URL = "https://api.weibo.com/oauth2/default.html";
		public boolean IsOK = false;
		public boolean IsConnected = false;
		public String PackageName = null;
		public String ActivityName = null;
		private WeakReference<Activity> mActivity = null;
		private String mAppId = null;
		private String[] mPermissions = null;
		private static final String WEIBO_SIGNATURE = "30820295308201fea00302010202044b4ef1bf300d06092a864886f70d010105050030818d310b300906035504061302434e3110300e060355040813074265694a696e673110300e060355040713074265694a696e67312c302a060355040a132353696e612e436f6d20546563686e6f6c6f677920284368696e612920436f2e204c7464312c302a060355040b132353696e612e436f6d20546563686e6f6c6f677920284368696e612920436f2e204c74643020170d3130303131343130323831355a180f32303630303130323130323831355a30818d310b300906035504061302434e3110300e060355040813074265694a696e673110300e060355040713074265694a696e67312c302a060355040a132353696e612e436f6d20546563686e6f6c6f677920284368696e612920436f2e204c7464312c302a060355040b132353696e612e436f6d20546563686e6f6c6f677920284368696e612920436f2e204c746430819f300d06092a864886f70d010101050003818d00308189028181009d367115bc206c86c237bb56c8e9033111889b5691f051b28d1aa8e42b66b7413657635b44786ea7e85d451a12a82a331fced99c48717922170b7fc9bc1040753c0d38b4cf2b22094b1df7c55705b0989441e75913a1a8bd2bc591aa729a1013c277c01c98cbec7da5ad7778b2fad62b85ac29ca28ced588638c98d6b7df5a130203010001300d06092a864886f70d0101050500038181000ad4b4c4dec800bd8fd2991adfd70676fce8ba9692ae50475f60ec468d1b758a665e961a3aedbece9fd4d7ce9295cd83f5f19dc441a065689d9820faedbb7c4a4c4635f5ba1293f6da4b72ed32fb8795f736a20c95cda776402099054fccefb4a1a558664ab8d637288feceba9508aa907fc1fe2b1ae5a0dec954ed831c0bea4";

		public SinaConnection (Activity activity, String appId) {
			this.mActivity = new WeakReference (activity);
			this.mAppId = appId;
		}

		public void setPermissions (String[] permissions) {
			this.mPermissions = permissions;
		}

		public void onServiceDisconnected (ComponentName name) {
			this.IsConnected = false;
		}

		public void onServiceConnected (ComponentName name, IBinder service) {
			this.IsConnected = true;
			RemoteSSO remoteSSOservice = RemoteSSO.Stub.asInterface (service);

			try {
				this.PackageName = remoteSSOservice.getPackageName ();
				this.ActivityName = remoteSSOservice.getActivityName ();
				this.IsOK = this.startSingleSignOn ((Activity) this.mActivity.get (), REQUEST_CODE);
			} catch (RemoteException var5) {
				var5.printStackTrace ();
			}
			Log.i (TAG, "onServiceConnected: RemoteSSOService's IsConnected = " + this.IsConnected);
		}

		private boolean startSingleSignOn (Activity activity, int activityCode) {
			Log.i (TAG, "startSingleSignOn: +");
			boolean didSucceed = true;
			Intent intent = new Intent ();
			intent.setClassName (this.PackageName, this.ActivityName);
			intent.putExtra ("appKey", this.mAppId);
			intent.putExtra ("redirectUri", REDIRECT_URL);
			if (this.mPermissions != null && this.mPermissions.length > 0) {
				intent.putExtra ("scope", TextUtils.join (",", this.mPermissions));
			}

			if (!this.validateAppSignatureForIntent (activity, intent)) {
				return false;
			} else {
				try {
					Log.i (TAG, "startSingleSignOn: startActivityForResult() activityCode = " + activityCode);
					activity.startActivityForResult (intent, activityCode);
				} catch (ActivityNotFoundException var6) {
					didSucceed = false;
				}

				if (this.IsConnected) {
					this.IsConnected = this.isServiceAlive (activity);
					Log.i (TAG, "startSingleSignOn: IsConnected = " + IsConnected);
					if (this.IsConnected) {
						activity.getApplication ().unbindService (this);
						Log.i (TAG, "startSingleSignOn: unbindService ");
					}
				}
				Log.i (TAG, "startSingleSignOn: -");
				return didSucceed;
			}
		}

		private boolean validateAppSignatureForIntent (Context context, Intent intent) {
			PackageManager pm = context.getPackageManager ();
			ResolveInfo resolveInfo = pm.resolveActivity (intent, 0);
			if (resolveInfo == null) {
				Log.i (TAG, "validateAppSignatureForIntent: false (resolveInfo == null)");
				return false;
			} else {
				String packageName = resolveInfo.activityInfo.packageName;

				try {
					PackageInfo e = pm.getPackageInfo (packageName, 0x40);// INSTALL_ALL_USERS
					Signature[] var7 = e.signatures;
					int var8 = var7.length;

					for (int var9 = 0; var9 < var8; ++var9) {
						Signature signature = var7[var9];
						if (WEIBO_SIGNATURE.equals (signature.toCharsString ())) {
							Log.i (TAG, "validateAppSignatureForIntent: true");
							return true;
						}
					}
					Log.i (TAG, "validateAppSignatureForIntent: false (签名不匹配)");
					return false;
				} catch (PackageManager.NameNotFoundException var11) {
					Log.i (TAG, "validateAppSignatureForIntent: false (PackageManager.NameNotFoundException)");
					return false;
				}
			}
		}

		private boolean isServiceAlive (Context context) {
			ActivityManager activityManager = (ActivityManager) context.getSystemService (Context.ACTIVITY_SERVICE);
			List serviceList = activityManager.getRunningServices (100);
			if (serviceList.size () <= 0) {
				return false;
			} else {
				for (int i = 0; i < serviceList.size (); ++i) {
					String serviceName = ((ActivityManager.RunningServiceInfo) serviceList.get (i)).service.getClassName ();
					if (serviceName.equals (AUTH_SERVICE_NAME)) {
						return true;
					}
				}
				return false;
			}
		}
	}

	class AuthListener implements WeiboAuthListener {

		private ISSOHandler.AuthListener mListener = null;

		public AuthListener (ISSOHandler.AuthListener mListener) {
			this.mListener = mListener;
		}

		@Override
		public void onComplete (Bundle bundle) {
			Log.i (TAG, "onComplete: bundle = " + bundle.toString ());
			SinaSsoHandler.this.sinaPreferences.setAuthData (bundle).commit ();
			if (this.mListener != null) {
				this.mListener.onComplete (PlatformEnum.SINA_WEIBO,
						0, SinaSsoHandler.this.bundleTomap (bundle));
			}
		}

		@Override
		public void onWeiboException (WeiboException e) {
			Log.i (TAG, "onWeiboException: e = " + e.toString ());
			if (this.mListener != null) {
				this.mListener.onError (PlatformEnum.SINA_WEIBO, 0, new Throwable (e));
			}
		}

		@Override
		public void onCancel () {
			Log.i (TAG, "onCancel: ");
			if (this.mListener != null) {
				this.mListener.onCancel (PlatformEnum.SINA_WEIBO, 0);
			}
		}
	}
}
